<template>
  <div>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
        <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-house" style="font-weight: bold">&nbsp;&nbsp;后台管理</i>
        </el-breadcrumb-item>
        <el-breadcrumb-item><i class="el-icon-s-data">&nbsp;&nbsp;财务管理</i></el-breadcrumb-item>
        <el-breadcrumb-item><i class="el-icon-edit-outline">&nbsp;&nbsp;工资在线修改</i></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!--  气泡输入框  -->
    <div id="dialog">
      <el-dialog
          :modal-append-to-body="false"
          title="收货地址"
          :visible.sync="dialogFormVisible"
          width="80%">
        <el-form
            :model="editForm"
            :rules="rules"
            ref="editForm"
            label-width="100px"
            style="margin-right: 25px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="月份:" prop="prop0">
                <el-select v-model="editForm.prop0" placeholder="请选择月份">
                  <el-option
                      v-for="item in months"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名:" prop="name">
                <el-input v-model="editForm.name" placeholder="输入姓名"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="职员ID:" prop="prop1">
                <el-input v-model="editForm.prop1" placeholder="输入职员ID"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入职时间:" prop="prop3">
                <el-date-picker
                    v-model="editForm.prop3"
                    type="date"
                    placeholder="选择入职时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="部门名称:" prop="prop4">
                <el-input v-model="editForm.prop4" placeholder="请输入部门名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作职位:" prop="prop5">
                <el-input v-model="editForm.prop5" placeholder="请输入工作职位"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="调休天数:" prop="prop6">
                <el-input v-model="editForm.prop6" placeholder="请输入调休天数"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出勤天数:" prop="prop7">
                <el-input v-model="editForm.prop7" placeholder="请输入出勤天数"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="基本工资:" prop="prop8">
                <el-input v-model="editForm.prop8" placeholder="请输入基本工资"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="岗位工资:" prop="prop9">
                <el-input v-model="editForm.prop9" placeholder="请输入岗位工资"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="津贴:" prop="prop10">
                <el-input v-model="editForm.prop10" placeholder="请输入津贴"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="公积金:" prop="prop11">
                <el-input v-model="editForm.prop11" placeholder="请输入公积金"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工龄工资:" prop="prop12">
                <el-input v-model="editForm.prop12" placeholder="请输入工龄工资"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工资克扣:" prop="prop13">
                <el-input v-model="editForm.prop13" placeholder="请输入工资克扣"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="克扣备注:" prop="prop14">
            <el-input v-model="editForm.prop14" placeholder="输入克扣备注"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="20">
              <el-form-item label="工资合计:" prop="prop15">
                <el-input v-model="editForm.prop15" placeholder="输入工资合计"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item style="float: right">
                <el-button type="primary"@click="compute" style="background-color: white;border-color: gray">
                  <i class="el-icon-thumb" style="color:gray;font-size: 100%">&nbsp;&nbsp;计算</i>
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" @click="updateForm" style="color: white">修改</el-button>
            <el-button type="warning" @click="dialogFormVisible = false" style="color: white">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

    <div class="data-canRead">
      <el-divider content-position="left">工资Excel文件在线修改</el-divider>
      <div id="Excel">
        <!-- 上传 -->
        <el-upload
            action
            accept=".xlsx, .xls"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handle">
          <el-button
              type="primary"
              class="imExcelBtn"><i class="el-icon-upload2" style="color:white;">打开Excel</i>
          </el-button>
        </el-upload>
      </div>
      <el-divider content-position="left">数据表查询</el-divider>
      <el-empty v-if="!tableKey" description="暂无数据...请上传文件"></el-empty>
      <div class="Excel">
        <!-- 表格名称及导出和关闭预览的按钮 -->
        <div class="excelName" v-if="tableKey">
          <div>
            <el-input
                placeholder="请输入姓名"
                v-model="searchName"
                style="width: 200px;"
                clearable
            ></el-input>
            <el-button @click="searchByName(true)" size="90%" type="primary"><i class="el-icon-search" style="color: white"></i></el-button>
          </div>

          <div id="top">{{ excelName }}<a href="#bottom" style="font-size: 10px">(到底部)</a></div>
          <div>
            <el-button type="success" @click="exportExcel"><i class="el-icon-upload2" style="color:white;">&nbsp;&nbsp;文件导出</i>
            </el-button>
            <el-button type="danger" @click="closeExcel"><i style="color:white;"
                                                            class="el-icon-close">&nbsp;&nbsp;关闭预览</i></el-button>
          </div>
        </div>
        <!-- 表格 -->
        <el-table
            :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
            style="width: 100%"
            :key="tableKey"
            :header-cell-style="{background: 'grey',color: 'white'}"
            v-if="tableKey"
            id="excelTable"
            border
            stripe>
          <!-- 第一个el-table-column 可根据需求删除-->
          <el-table-column
              header-align="center"
              align="center"
              type="index"
              label="序号"
              width="100">
          </el-table-column>
          <el-table-column
              v-for="(item, index) in tableColumn"
              header-align="center"
              :key="index"
              :prop="item.prop"
              :label="item.label"
              :width="item.width">
          </el-table-column>
          <el-table-column label="操作" width="100px" header-align="center">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="primary"
                  circle
                  @click="handleEdit(scope.$index, scope.row)"><i class="el-icon-edit" style="color: white"></i>
              </el-button>
              <el-button
                  size="mini"
                  type="danger"
                  circle
                  @click="handleDelete(scope.$index, scope.row)"><i class="el-icon-delete" style="color: white"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination align='center' @size-change="handleSizeChange"
                       id="bottom"
                       @current-change="handleCurrentChange"
                       v-if="tableKey"
                       :current-page="currentPage"
                       :page-sizes="[1,5,10,20,tableData.length]"
                       :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="tableData.length">
        </el-pagination>
        <div style="float: right;margin-right: 20px"><a href="#top" style="font-size: 10px;">返回顶部</a></div>
      </div>
    </div>
  </div>
</template>
<script>
import * as XLSX from "xlsx/xlsx.mjs";
import FileSaver from "file-saver";

export default {
  data() {
    return {
      months:[
        {label:'一月',value:1},
        {label:'二月',value:2},
        {label:'三月',value:3},
        {label:'四月',value:4},
        {label:'五月',value:5},
        {label:'六月',value:6},
        {label:'七月',value:7},
        {label:'八月',value:8},
        {label:'九月',value:9},
        {label:'十月',value:10},
        {label:'十一月',value:11},
        {label:'十二月',value:12},
      ],
      searchName: '',//根据名称搜索

      tableKey: false, //表格的key及显示与隐藏
      excelName: '', //excel表格名称
      excelHeader: [], //excel的表头
      tableData: [], //表格数据
      tableDataCopy: [], //表格数据备份
      tableColumn: [], //表格的表头

      currentPage: 1,//默认页码
      pageSize: 10,//单页最多数据数

      dialogFormVisible:false,
      formIndex:'',
      rules: {
        month: [
          {required: true, message: "请选择月份", trigger: 'change'},
        ],
        employeeId: [
          {required: true, message: "请输入职员ID", trigger: 'blur'},
          {pattern: /^[0-9]+$/, message: "请输入数字", trigger: 'blur'}
        ],
        name: [
          {required: true, message: "请输入姓名", trigger: 'blur'},
          {pattern: /[\u4E00-\u9FA5]/, message: "请输入中文", trigger: 'blur'}
        ],
        hiredate: [
          {required: true, message: "请选择入职日期", trigger: 'change'},
        ],
        deptName: [
          {required: true, message: "请输入部门名称", trigger: 'blur'},
          {pattern: /[\u4E00-\u9FA5]/, message: "请输入中文", trigger: 'blur'}
        ],
        job: [
          {required: true, message: "请输入工作职位", trigger: 'blur'},
          {pattern: /[\u4E00-\u9FA5]/, message: "请输入中文", trigger: 'blur'}
        ],
        compensatoryDays: [
          {required: true, message: "请输入调休天数", trigger: 'blur'},
          {pattern: /^[0-9]+$/, message: "请输入数字", trigger: 'blur'}
        ],
        attendanceDays: [
          {required: true, message: "请输入出勤天数", trigger: 'blur'},
          {pattern: /^[0-9]+$/, message: "请输入数字", trigger: 'blur'}
        ],
        baseFunds: [
          {required: true, message: "请输入基本工资", trigger: 'blur'},
          {pattern: /^[0-9]+$/, message: "请输入数字", trigger: 'blur'}
        ],
        postFunds: [
          {required: true, message: "请输入岗位工资", trigger: 'blur'},
          {pattern: /^[0-9]+$/, message: "请输入数字", trigger: 'blur'}
        ],
        subsidy: [
          {required: true, message: "请输入津贴", trigger: 'blur'},
          {pattern: /^[0-9]+$/, message: "请输入数字", trigger: 'blur'}
        ],
        publicAccumulationFunds: [
          {required: true, message: "请输入公积金", trigger: 'blur'},
          {pattern: /^[0-9]+$/, message: "请输入数字", trigger: 'blur'}
        ],
        jobLifeFunds: [
          {required: true, message: "请输入工龄工资", trigger: 'blur'},
          {pattern: /^[0-9]+$/, message: "请输入数字", trigger: 'blur'}
        ],
        lessFunds: [
          {required: true, message: "请输入工资克扣", trigger: 'blur'},
          {pattern: /^[0-9]+$/, message: "请输入数字", trigger: 'blur'}
        ],
        sumSalary: [
          {required: true, message: "请输入工资合计", trigger: 'blur'},
          {pattern: /^[0-9]+$/, message: "请输入数字", trigger: 'blur'}
        ],
        remarks: [
          {required: true, message: "请输入备注", trigger: 'blur'},
          {pattern: /[\u4E00-\u9FA5]/, message: "请输入中文", trigger: 'blur'}
        ],
      },//修改表格输入格式
      editForm:{
        prop0: '',
        prop2: '',
        name: '',
        prop3: '',
        prop4: '',
        prop5: '',
        /*工资核算天数为26-5*/
        prop6: '',
        prop7: '',
        prop8: '',
        prop9: '',
        prop10: '',
        prop11: '',
        prop12: '',
        prop13: '',
        prop14: '',
        prop15: '',},//修改表格

    };
  },
  methods: {
    readFile(file) {
      //文件读取
      return new Promise((resolve) => {
        let reader = new FileReader();
        reader.readAsBinaryString(file); //以二进制的方式读取
        reader.onload = (ev) => {
          resolve(ev.target.result);
        };
      });
    },
    // 上传文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    async handle(ev) {
      //改变表格key值
      this.tableKey = true;
      let file = ev.raw;
      this.excelName = file.name;
      //截取表格文件名
      this.excelName = this.excelName.substring(
          0,
          this.excelName.lastIndexOf(".")
      );
      console.log("上传的未解析源文件", file);
      if (!file) {
        console.log("文件打开失败");
        return;
      } else {
        let data = await this.readFile(file);
        let workbook = XLSX.read(data, {type: "binary"}); //解析二进制格式数据
        console.log("二进制数据的解析:", workbook);
        let worksheet = workbook.Sheets[workbook.SheetNames[0]]; //获取第一个Sheet
        // 调用解析表头方法
        this.getHeader(worksheet);
        let result = XLSX.utils.sheet_to_json(worksheet); //转换为json数据格式
        console.log("最终解析的 json 格式数据:", result);
        this.tableData = result;
        // 调用处理表头函数
        this.setTable();
      }
    },
    // 解析出表格表头
    getHeader(sheet) {
      // const XLSX = XLSX;
      const headers = [];
      const range = XLSX.utils.decode_range(sheet["!ref"]); // worksheet['!ref'] 是工作表的有效范围
      let C;
      /* 获取单元格值 start in the first row */
      const R = range.s.r; // 行 // C 列
      let i = 0;
      for (C = range.s.c; C <= range.e.c; ++C) {
        var cell =
            sheet[
                XLSX.utils.encode_cell({c: C, r: R})
                ]; /* 根据地址得到单元格的值find the cell in the first row */
        var hdr = "UNKNOWN" + C; // 如果有空表头，会替换为您想要的默认值replace with your desired default
        // XLSX.utils.format_cell 生成单元格文本值
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell);
        if (hdr.indexOf("UNKNOWN") > -1) {
          if (!i) {
            hdr = "__EMPTY";
          } else {
            hdr = "__EMPTY_" + i;
          }
          i++;
        }
        headers.push(hdr);
      }
      // 保存至data中
      this.excelHeader = headers;
      return headers;
    },
    // 设置表格中英文映射
    setTable() {
      const headers = this.excelHeader;
      const excellist = this.tableData;

      const tableTitleData = []; // 存储表格表头数据
      const tableMapTitle = {}; // 设置表格内容中英文对照用
      headers.forEach((_, i) => {
        console.log(i)
        console.log(_)
        if (_ === '职员姓名') {
          tableMapTitle[_] = "name";
          tableTitleData.push({
            prop: "name",
            label: _,
            width: 100,
          });
        } else if (_ === '工作职位'){
          tableMapTitle[_] = "prop" + i;
          tableTitleData.push({
            prop: "prop" + i,
            label: _,
            width: 200,
          });
        } else if (_ === '克扣备注'){
          tableMapTitle[_] = "prop" + i;
          tableTitleData.push({
            prop: "prop" + i,
            label: _,
            width: 500,
          });
        } else {
          tableMapTitle[_] = "prop" + i;
          tableTitleData.push({
            prop: "prop" + i,
            label: _,
            width: 100,
          });
        }
      });
      console.log("表格头标题：", tableTitleData);
      // 映射表格内容属性名为英文
      const newTableData = [];
      excellist.forEach((_) => {
        const newObj = {};
        Object.keys(_).forEach((key) => {
          newObj[tableMapTitle[key]] = _[key];
          // console.log("_:" + _)
          // console.log("key:" + key)
          // console.log("tableMapTitle[key]:" + tableMapTitle[key]);
          // console.log("_[key]:" + _[key]);
        });
        newTableData.push(newObj);
      });
      console.log("表格数据：", newTableData);
      this.tableColumn = tableTitleData;
      this.tableData = newTableData;
      this.tableDataCopy = newTableData;
    },
    // 关闭表格预览
    closeExcel() {
      this.tableKey = false;
      //表格数据置空
      this.tableData = [];
      this.tableDataCopy = [];
      this.tableColumn = [];
    },
    submit(forName) {

    },
    //页码更改
    exportExcel() {
      this.$message({
        type: 'success',
        message: `数据导出中...`
      });
      this.pageSize = this.tableData.length;
      this.currentPage = 1;

      this.exportExcel1()
    },
    //导出表格为Excel
    exportExcel1() {
      // 导出的内容只做解析，不进行格式转换
      let xlsxParam = {raw: true};

      let table = document.querySelector('#excelTable').cloneNode(true);

      let wb = XLSX.utils.table_to_book(table, xlsxParam)

      let wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });

      try {
        FileSaver.saveAs(new Blob([wbout], {type: "application/octet-stream"}), '员工工资表.xlsx');
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    /*表格*/
    //每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.currentPage = 1;
      this.pageSize = val;
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
    //表格内容删除
    handleDelete(index, row) {
      this.tableData.splice(index, 1);
    },
    //表内容修改
    handleEdit(index,row){
      this.dialogFormVisible = true;
      this.editForm = this.tableData[index];
      this.formIndex = index;
    },
    updateForm(){
      this.tableData[this.formIndex] = this.editForm;
      /*关闭对话框*/
      this.dialogFormVisible = false;
    },
    searchByName(bool) {
      this.currentPage = 1;
      if (bool) {
        let tableData = [];
        if (this.searchName) {
          this.tableData.filter((item) => {
            console.log(item.name)
            console.log(this.searchName)
            console.log(item.name.indexOf(this.searchName))
            if (item.name.indexOf(this.searchName) !== -1) {
              tableData.push(item);
              console.log(tableData);
            }
          });
        }
        this.tableData = tableData;
        console.log(this.tableData)
      }
    },
    compute() {
      let sumSalary =
          (
              parseInt(this.editForm.prop8) +
              parseInt(this.editForm.prop9) +
              parseInt(this.editForm.prop10) +
              parseInt(this.editForm.prop11) +
              parseInt(this.editForm.prop12) -
              parseInt(this.editForm.prop13)
          ) * (
              parseInt(this.editForm.prop7) -
              parseInt(this.editForm.prop6)
          ) / 30 ;
      this.$set(this.editForm,'prop15',sumSalary);
    },
  },
  watch: {
    searchName(newValue) {
      if (newValue) {
        this.searchByName(true);
      } else {
        this.searchByName(false);
        this.tableData = this.tableDataCopy;
      }
    }
  }
};

</script>

<style scoped>
.excelName {
  display: flex;
  justify-content: space-between;
  font-size: 30px;
  margin-bottom: 20px;
}

.imExcelBtn {
  margin: 10px 0;
  background-color: rgba(37, 83, 255, 0.9);
  margin-left: 20px;
  margin-bottom: 20px;
}

* {
  color: black;
}

.data-canRead {
  width: 100%;
  margin-top: 15px;
  box-shadow: 0px 5px 5px #8d858a;
  float: left;
  margin-right: 16px;
  background-color: white;
}

</style>
